package com.atguigu.gmall.realtime.web.controller;


import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.realtime.web.bean.NameValueBean;
import com.atguigu.gmall.realtime.web.service.TradeService;
import com.atguigu.gmall.realtime.web.util.DateFormatUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/trade")
public class TradeController {


    @Autowired
    TradeService tradeService;



//{
//  "status": 0,
//  "msg": "",
//  "data": 1201038.5431585948
//}
    @RequestMapping ("/totalamount")
    public  String getTotalAmount(@RequestParam(value = "dt",required = false )String dt){
        System.out.println(dt.length());
        if(dt==null){
      //      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
      //       dt = simpleDateFormat.format(new Date());
               dt = DateFormatUtil.toDate(System.currentTimeMillis());
        }

        BigDecimal totalAmount = tradeService.getTotalAmount(dt);

        String resultJson=" {\n" +
                "  \"status\": 0,\n" +
                "   \"msg\": \"\",\n" +
                "   \"data\": "+totalAmount.setScale(2,RoundingMode.HALF_UP)+"\n" +
                " }";

        return resultJson;

    }

    ///  省市交易额统计
    //{
    //  "status": 0,
    //  "msg": "",
    //  "data": {
    //    "mapData": [
    //      {
    //        "name": "内蒙古",
    //        "value": 1200
    //      },
    //      {
    //        "name": "上海",
    //        "value": 10
    //      }
    //    ],
    //    "valueName": "订单数"
    //  }
    //}
    @RequestMapping("/province/order_amount")
    public  String getOrderAmountGroupByProvince(@RequestParam(value = "dt",required = false )String dt){
        if(dt==null){ //如果没有日期 则取今天
            dt = DateFormatUtil.toDate(System.currentTimeMillis());
        }
        //取得结果列表
        List<NameValueBean> nameValueBeanList= tradeService.getOrderAmountByProvince(  dt);
       //把结果组合成json
        List<String> mapJsonList = nameValueBeanList.stream().map(nameValueBean -> JSON.toJSONString(nameValueBean)).collect(Collectors.toList());
        String mapDataJson = StringUtils.join(mapJsonList, ",");
        //把json动态部分和固定部分拼接在一起
        String datajson=" {\n" +
                "       \"status\": 0,\n" +
                "       \"msg\": \"\",\n" +
                "       \"data\": {\n" +
                "         \"mapData\": [\n" +
                               mapDataJson+
                "         ],\n" +
                "         \"valueName\": \"订单金额\"\n" +
                "       }\n" +
                "     }";


        return datajson;

    }


}
